<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px" @submit.prevent>
      <el-form-item label="质检任务单号" prop="inboundOrderCode">
        <el-input
          v-model.trim="queryParams.inboundOrderCode"
          placeholder="请输入任务单号"
          clearable
          @keyup.enter="handleQuery"
          style="width: 175px"
        />
      </el-form-item>      
      <el-form-item label="任务类型" prop="qualityType">
        <el-select
          v-model="queryParams.qualityType"
          placeholder="请选择任务类型"
          clearable
          style="width: 175px"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in quality_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择任务状态"
          clearable
          style="width: 175px"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in quality_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            
          />
        </el-select>
      </el-form-item>
      <el-form-item label="紧急程度" prop="isUrgent">
        <el-select
          v-model="queryParams.isUrgent"
          placeholder="请选择紧急程度"
          clearable
          style="width: 175px"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in is_urgent"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <!-- <el-button
          type="success"
          @click="goTo"
        >质检作业</el-button> -->
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:header:add']"
        >新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:header:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:header:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:header:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Checked"
          :loading="btn.start"
          :disabled="multiple"
          @click="startQuality"
        >批量开始质检</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <TableScrollContainer :topHeight="220">
      <template #default="{ tableHeight }">
    <el-table v-loading="loading" :data="headerList" @selection-change="handleSelectionChange" :height="tableHeight" border>
      <el-table-column type="selection" :selectable="isRowSelectable"  width="55" align="center" />
      <el-table-column label="质检任务单号" align="center" prop="qualityCode" />
      <el-table-column label="任务类型" align="center" prop="qualityType">
        <template #default="scope">
          <dict-tag :options="quality_type" :value="scope.row.qualityType"/>
        </template>
      </el-table-column>
        <el-table-column label="紧急程度" align="center" prop="isUrgent">
        <template #default="scope">
          <dict-tag :options="is_urgent" :value="scope.row.isUrgent"/>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="quality_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作人ID" align="center" prop="operatorId" /> -->
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="completeTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.completeTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="410" fixed="right">
        <template #default="scope">
          <!-- 修改点: 真实按钮和占位按钮样式完全一致 -->
          <el-button
            v-if="scope.row.qualityType === 1"
            type="primary"
            icon="Checked"
            :disabled="scope.row.status !== 0"
            :loading="btn.startSingle === scope.$index"
            @click="startQuality(scope.row, scope.$index)"
          >开始质检</el-button>
          <!-- 占位按钮，样式与真实按钮完全相同，但内容为空 -->
          <el-button
            v-else
            type="primary"
            icon="Checked"
            disabled
            style="color: transparent; background-color: transparent; border-color: transparent;"
          >开始质检</el-button>
          
          <el-button
            type="warning"
            icon="Close"
            :disabled="scope.row.status !== 0"
            :loading="btn.cancel === scope.$index"
            @click="cancelQuality(scope.row, scope.$index)"
          >取消</el-button>
          <el-button type="primary" @click="checkDetail(scope.row)">查看详情</el-button>
          <!-- <el-button type="success" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:header:edit']">修改</el-button> -->
          <el-button type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:header:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page-sizes="[10, 30, 50, 100]"
          v-model:page="queryParams.pageNum"  
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
      </template>
    </TableScrollContainer>

    <!-- 添加或修改质检单头对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" :close-on-click-modal="false">
      <el-form ref="headerRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="质检类型" prop="qualityType">
          <el-select v-model="form.qualityType" placeholder="请选择质检类型">
            <el-option
              v-for="dict in quality_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="质检单状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择质检单状态">
            <el-option
              v-for="dict in quality_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作人ID" prop="operatorId">
          <el-input v-model="form.operatorId" placeholder="请输入操作人ID" />
        </el-form-item>
        <!-- <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="完成时间" prop="completeTime">
          <el-date-picker clearable
            v-model="form.completeTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择完成时间">
          </el-date-picker>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="QualityOrder">
import { listHeader, getHeader, delHeader, addHeader, updateHeader, qualityAPI, cancelAPI } from "@/api/work/qualityOrder"
import useListDataStore from '@/store/modules/listData'
import TableScrollContainer from '@/components/Pagetable/TableScrollContainer.vue'
const useListData = useListDataStore()
const { proxy } = getCurrentInstance()
const { quality_type, quality_status,is_urgent } = proxy.useDict('quality_type', 'quality_status', 'is_urgent')

const headerList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const btn = reactive({
  start: false,
  startSingle: '',
  cancel: ''
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    qualityType: null,
    status: null,
    operatorId: null,
    startTime: null,
    completeTime: null,
  },
  rules: {
    qualityType: [
      { required: true, message: "质检类型不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "质检单状态不能为空", trigger: "change" }
    ],
    operatorId: [
      { required: true, message: "操作人ID不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询质检单头列表 */
function getList() {
  loading.value = true
  listHeader(queryParams.value).then(res => {
    if (res.errCode === '1') {
      headerList.value = res.data.page.records
      total.value = res.data.page.total
      loading.value = false
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    qualityCode: null,
    qualityType: null,
    status: null,
    operatorId: null,
    startTime: null,
    completeTime: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("headerRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.qualityCode)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加质检单头"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _qualityCode = row.qualityCode || ids.value
  console.log(_qualityCode)
  getHeader(_qualityCode).then(res => {
    // console.log(res)
    form.value = res.data.qualityTaskHeader
    open.value = true
    title.value = "修改质检单头"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["headerRef"].validate(valid => {
    if (valid) {
      if (form.value.qualityCode != null) {
        updateHeader(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      } else {
        addHeader(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _qualityCodes = row.qualityCode || ids.value
  proxy.$modal.confirm('是否确认删除质检单头编号为"' + _qualityCodes + '"的数据项？').then(function() {
    return delHeader(_qualityCodes)
  }).then(res => {
    if (res.errCode === '1') {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    } else {
      proxy.$modal.msgError(res.msg)
    }
  }).catch(() => {})
}

const checkDetail = (row) => {
  console.log(row)
  proxy.$router.push(`/qualityManagement/qualityDetail?qualityCode=${row.qualityCode}`)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('api/qualityTaskHeader/export', {
    ...queryParams.value
  }, `质检单数据_${new Date().getTime()}.xlsx`)
}

getList()

// 修改点: 修改isRowSelectable函数，只有超期质检(qualityType为1)且状态为0的记录才能被选中
const isRowSelectable = (val) => {
  return val.status === 0 && val.qualityType === 1
}

// 修改点: 修改startQuality函数，成功后弹出确认框询问是否跳转
const startQuality = async(row, index) => {
  try {
    if (index !== undefined) {
      btn.startSingle = index
    } else {
      btn.start = true
    }
    const _qualityCodes = row.qualityCode ? [row.qualityCode] : row.quality || ids.value
    const res = await qualityAPI({
      qualityCodes: _qualityCodes
    })
    if (res.errCode === '1') {
      proxy.$modal.msgSuccess("执行成功")
      getList()
      // 弹出确认框，询问是否前往作业页面
      proxy.$modal.confirm('质检已开始，是否前往作业页面？').then(() => {
        // 用户点击确认，执行跳转
        goTo()
      }).catch(() => {
        // 用户点击取消，不做任何操作
        proxy.$modal.msgInfo('已取消前往');
      })
    } else {
      proxy.$modal.msgError(res.msg)
    }
  } finally {
    if (index !== undefined) {
      btn.startSingle = ''
    } else {
      btn.start = false
    }
  }
}

const cancelQuality = async(row, index) => {
  try {
    btn.cancel = index
    const _qualityCodes = row.qualityCode
    const res = await cancelAPI({
      qualityCode: _qualityCodes
    })
    if (res.errCode === '1') {
      proxy.$modal.msgSuccess("取消成功")
      getList()
    } else {
      proxy.$modal.msgError(res.msg)
    }
  } finally {
    btn.cancel = ''
  }
}

// 修改点: 将goTo函数逻辑用于跳转
const goTo = () => {
  proxy.$router.push('/qualityManagement/qualityWork')
}
</script>
